#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.Text;

namespace Osh.ProgDvb
{
	public class ProgDvbPacketStream : PipePacketStream
	{
		private ProgDvbApplication _player;

		public ProgDvbPacketStream(ProgDvbApplication player, ushort id, bool endOnChannelChange)
			: base(Initialize(player, id))
		{
			this.ReadThrough = true;
			_player = player;
			if(endOnChannelChange)
				player.MediaChange += new EventHandler<Osh.Media.MediaChangeArgs>(Player_MediaChange);
		}

		private void Player_MediaChange(object sender, Osh.Media.MediaChangeArgs e)
		{
			_player.RemovePacketFilter(base.PipeName);
		}

		public override void Close()
		{
			// First remove the filter to close the pipe from the other side so
			// we won't be blocked trying to close the handle while reading from it on this side.
			_player.RemovePacketFilter(base.PipeName);
			base.Close();
		}

		private static string Initialize(ProgDvbApplication player, ushort id)
		{
			string filterName = GenerateFilterName();
			player.AddPacketFilter(filterName, id, 10000, 10000, false);
			return filterName;
		}

		private static string GenerateFilterName()
		{
			return "Osh.ProgDvb.ProgDvbPacketStream-" + Guid.NewGuid().ToString().ToUpperInvariant();
		}
	}
}
